package org.mozhu.mboot.admin.maintain.email.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.mozhu.mboot.admin.Constants;
import org.mozhu.mboot.admin.GlobalSettings;
import org.mozhu.mboot.admin.maintain.email.entity.EmailNotification;
import org.mozhu.mboot.admin.maintain.email.service.EmailNotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class EmailScheduledTask {

    @Autowired
    GlobalSettings globalSettings;
    @Autowired
    EmailNotificationService emailNotificationService;

    ExecutorService executorService = Executors.newFixedThreadPool(10, new CustomizableThreadFactory("Email-Notify-Thread-"));

    @Scheduled(fixedRate = 5 * Constants.SECONDS, initialDelay = 5 * Constants.SECONDS)
    public void sendEmailNotifications() {
        if (!globalSettings.isEmailTaskEnable()) {
            log.debug("sendEmailNotifications task disable");
            return;
        }
        log.debug("sendEmailNotifications task start");
        List<EmailNotification> pendingEmailNotifications = emailNotificationService.findPendingEmailNotifications();
        log.info("[{}] pending EmailNotifications found", pendingEmailNotifications.size());
        if (CollectionUtils.isEmpty(pendingEmailNotifications)) {
            return;
        }
        List<Callable<Void>> tasks = Lists.newArrayList();
        for (EmailNotification emailNotification : pendingEmailNotifications) {
            tasks.add(() -> {
                emailNotificationService.sendEmailNotification(emailNotification);
                return null;
            });
        }

        try {
            executorService.invokeAll(tasks);
        } catch (InterruptedException e) {
            log.error("sendEmailNotifications task failed", e);
        }
        log.debug("sendEmailNotifications task end");
    }

}
